﻿<%@ WebHandler Language="C#" Class="ZSMfgOrderMaintainHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.IO;
using NPOI.SS.UserModel;
using DatabaseAccess.DBUtility;
using System.Text.RegularExpressions;

public class ZSMfgOrderMaintainHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSMfgOrderIBusiness m_MfgOrderObj = uMESBusinessFactory.instance.GetuLMSMfgOrderObject();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSPartPlanIBusiness m_PartPlanObj = uMESBusinessFactory.instance.GetuLMSPartPlanObject();
    private uLMSRoutineTestIBusiness m_RoutineTestObj = uMESBusinessFactory.instance.GetuLMSRoutineTestObject();
    private uLMSIssueERPMaterialIbusiness m_issueData = uMESBusinessFactory.instance.GetuLMSIssueERPMaterialObject();
    private uLMSDispatchIBusiness m_DispatchObj = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    private const string TempOrderTypeList = "PD05,PD06,PD09,PD11,PD12,PD13,PD14";
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetMfgOrderData": //查询订单信息
                    GetMfgOrderData(context);
                    break;
                case "SaveMfgOrderData"://订单分厂计划保存
                    SaveMfgOrderData(context);
                    break;
                case "GetMfgOrderSplitData"://获取待订单分解数据
                    GetMfgOrderSplitData(context);
                    break;
                case "GetMfgMergeData"://获取订单--大阶段数据
                    GetMfgMergeData(context, null);
                    break;
                case "GetBomListbyWorkflowid"://获取部件对应工艺下的bom信息
                    GetBomListbyWorkflowid(context);
                    break;
                case "SaveTemplet"://保存模板
                    SaveTemplet(context);
                    break;
                case "ClearTemplet"://清除模板
                    ClearTemplet(context);
                    break;
                case "CalcContainerPlan"://计划时间计算
                    CalcContainerPlan(context);
                    break;
                case "SaveSessionToDB"://订单应用
                    SaveSessionToDB(context);
                    break;
                case "WgResultCheckChange"://部件信息--勾选-取消事件
                    WgResultCheckChange(context);
                    break;
                case "SaveProductPlan"://制定计划
                    SaveProductPlan(context);
                    break;
                case "UpdateMergeWorkFlow"://调整工艺
                    UpdateMergeWorkFlow(context);
                    break;
                case "WorkFlowDataChange"://部件工艺下拉选择
                    WorkFlowDataChange(context);
                    break;
                case "GetSGDData"://施工单查询（分页）
                    GetSGDData(context);
                    break;
                case "SplitTempOrder"://施工单分解--确认
                    SplitTempOrder(context);
                    break;
                case "GetJTDData"://技通单查询（分页）
                    GetJTDData(context);
                    break;
                case "TechnicalWorkflowForSplit"://技通单分解--确认
                    TechnicalWorkflowForSplit(context);
                    break;
                case "SplitNoMergeOrder"://分解无大阶段-子部件订单
                    SplitNoMergeOrder(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


    private void GetMfgOrderData(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("CurrentPageIndex", pageNumber);
        para.Add("PageSize", pageSize);
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("ZS", "ZS");
        if (!string.IsNullOrWhiteSpace(argPara["txtSGD"]))
        {
            para.Add("SGD", argPara["txtSGD"]);
        }
        else
        {
            para.Add("OrderStatus", argPara["ddlOrderStatus"]);
            para.Add("OrderTypeName", TempOrderTypeList);
            para.Add("OrderTypeIndex", argPara["ddlTaskType"].Equals("无物料号订单") ? "1" : "");
            para.Add("OrderCloseStatus", "0");
            if (!string.IsNullOrWhiteSpace(argPara["txtMachine"])) { para.Add("Machine", argPara["txtMachine"]); }
            if (!string.IsNullOrWhiteSpace(argPara["ScanmfgOrderName"])) { para.Add("mfgOrderName", argPara["ScanmfgOrderName"]); }
            if (!string.IsNullOrWhiteSpace(argPara["ScanmfgOrderNameLast"])) { para.Add("mfgOrderNameLast", argPara["ScanmfgOrderNameLast"]); }
            //if (!string.IsNullOrWhiteSpace(argPara["txtMonthPlan"])) { para.Add("MonthPlan", argPara["txtMonthPlan"]); }
        }
        var result = m_MfgOrderObj.GetMfgOrderData(para);
        if (result.Result)
        {
            //对订单工艺的特殊处-- '1，未分解 2，已分解
            result.DBTable = FillMfgDatatable(result.DBTable, argPara["ddlOrderStatus"]);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private DataTable FillMfgDatatable(DataTable dt, string orderstatus)
    {
        var strsql = @"SELECT p.productid,wb.workflowname,wf.workflowrevision,wf.workflowid,
                    pf.productfamilyid,pf.productfamilyname
                    FROM product p
                    LEFT JOIN productworkflowmapping pw ON p.productid=pw.productid
                    LEFT JOIN workflow wf ON wf.workflowid=pw.workflowid
                    LEFT JOIN workflowbase wb ON wb.workflowbaseid=wf.workflowbaseid
                    LEFT JOIN workflowproductfamilylist wff ON wff.workflowid=wf.workflowid
                    LEFT JOIN productfamily pf ON pf.productfamilyid=wff.productfamilylistid 
                    WHERE p.productid='{0}' AND wf.workflowid=wb.revofrcdid  " + (m_UserInfo.FactoryEName.Equals("试车厂") ? "" : "and wf.phasenode IS NULL");
        strsql += " order by wf.workflowid desc";
        var strsqlEng = @"SELECT ep.productid,nvl(wb.workflowname,ep.workflowname)workflowname,nvl(wf.workflowrevision,ep.workflowver)workflowrevision,nvl(wf.workflowid,ep.workflowid) workflowid,pf.productfamilyid,pf.productfamilyname 
                from enginepartplan ep 
                LEFT JOIN workflowstep ws ON ws.workflowstepid=ep.workflowstepid
                LEFT JOIN workflow wf ON wf.workflowid=ws.workflowid
                LEFT JOIN workflowbase wb ON wb.workflowbaseid=wf.workflowbaseid
                LEFT JOIN workflowproductfamilylist wff ON wff.workflowid=nvl(wf.workflowid,ep.workflowid)
                LEFT JOIN productfamily pf ON pf.productfamilyid=wff.productfamilylistid
                where ep.mfgorderid='{0}' and ep.productid='{1}' AND ep.type='1' AND ROWNUM=1";
        DataTable dttemp = new DataTable();
        foreach (DataRow dr in dt.Rows)
        {
            if (orderstatus.Equals("1")) //未分解
            {
                dttemp = DatabaseHelper.Query_ReturnDatTable(String.Format(strsql, dr["productid"].ToString()));
            }
            else //'已分解 施工单 普通任务单
            {
                dttemp = DatabaseHelper.Query_ReturnDatTable(String.Format(strsqlEng, dr["mfgorderid"].ToString(), dr["productid"].ToString()));
                if (dttemp.Rows.Count == 0)
                {
                    dttemp = DatabaseHelper.Query_ReturnDatTable(String.Format(strsql, dr["productid"].ToString()));
                }
            }
            if (dttemp.Rows.Count > 0)
            {
                dr["WORKFLOWID"] = dttemp.Rows[0]["WORKFLOWID"].ToString();
                dr["productfamilyname"] = dttemp.Rows[0]["productfamilyname"].ToString();
                dr["productfamilyid"] = dttemp.Rows[0]["productfamilyid"].ToString();
                dr["WORKFLOWNAME"] = dttemp.Rows[0]["WORKFLOWNAME"].ToString();
                dr["WORKFLOWREVISION"] = dttemp.Rows[0]["WORKFLOWREVISION"].ToString();
            }
        }

        return dt;
    }

    private void SaveMfgOrderData(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        var docount = 0;
        var spanDays = Convert.ToInt32(argPara["txtSpan"]);//连台时间间隔（天）
        var PlanedMonth = argPara["ddlYears"] + argPara["ddlMonth"];//年月
        var StartDate = argPara["txtplanStartDate"];//计划开始日期
        var orderTypeName = string.Empty;
        var strFamily = string.Empty;
        var int_choose = 0;
        var tmpPlan = String.Empty;
        foreach (DataRow row in dt.Rows)
        {
            int_choose += 1;
            if (string.IsNullOrWhiteSpace(strFamily)) { strFamily = row["ProductFamilyName"].ToString(); }
            else
            {
                if (!strFamily.Equals(row["ProductFamilyName"].ToString()))
                {
                    result.Message = "请选择相同机型!";
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
            }
            if (!string.IsNullOrWhiteSpace(row["FactoryMonth"].ToString())) { tmpPlan = row["FactoryMonth"].ToString(); }
            if (int_choose > 1 && string.IsNullOrWhiteSpace(tmpPlan))
            {
                result.Message = "已经维护的订单请单个更改!";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        foreach (DataRow row in dt.Rows)
        {
            if (!string.IsNullOrWhiteSpace(argPara["ddlType"]))
            {
                if (string.IsNullOrWhiteSpace(orderTypeName))
                {
                    orderTypeName = row["orderTypeName"].ToString();
                }
                else
                {
                    if (!orderTypeName.Equals(row["orderTypeName"].ToString()))
                    {
                        result.Message = "请选择同类型的订单";
                        context.Response.Write(JsonConvert.SerializeObject(result));
                        return;
                    }
                }
            }
            StartDate = Convert.ToDateTime(StartDate).AddDays(docount * spanDays).ToString("yyyy-MM-dd");
            docount += 1;
            var para = new Dictionary<string, string>();
            para.Add("FactoryMonth", string.IsNullOrWhiteSpace(PlanedMonth) ? "" : PlanedMonth);
            para.Add("FactoryStratDate", StartDate);
            para.Add("Notes", argPara["txtNote"]);
            para.Add("FactoryEndDate", "");
            para.Add("MfgOrderID", row["MfgOrderID"].ToString());
            try
            {
                result.Result = (bool)m_MfgOrderObj.UpdateMfgOrderInfo(para);//
                if (result.Result)
                {
                    var paraAttribute = new Dictionary<string, string>();
                    paraAttribute.Add("MfgOrderName", row["MfgOrderName"].ToString());
                    paraAttribute.Add("Name", "订单类别");
                    paraAttribute.Add("AttributeValue", argPara["ddlType"]);
                    paraAttribute.Add("MfgOrderID", para["MfgOrderID"]);
                    if (!string.IsNullOrWhiteSpace(argPara["ddlType"]))
                    {
                        var mfgType = string.IsNullOrWhiteSpace(row["mfgType"].ToString()) ? string.Empty : row["mfgType"].ToString();
                        if (!paraAttribute["AttributeValue"].Equals(mfgType))
                        {//订单类别（原先与选择）不一致；则更新
                            result.Result = SaveMfgOrderAttribute(paraAttribute);//---------
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                result.Message = "订单更新失败,原因：" + row["MfgOrderName"].ToString() + ":" + ex.Message;
                break;
            }
        }
        result.Message = result.Result ? "订单更新成功" : "订单更新失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private bool SaveMfgOrderAttribute(Dictionary<string, string> para)
    {
        DataTable dt = m_CommonObj.GetTableInfo("Userattribute", "Parentid", para["MfgOrderID"]);//------------
        //订单
        var dataList = new List<ClientAPIEntity>();
        var dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = para["MfgOrderName"];
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        dataList.Add(dataEntity);
        //属性
        var m_AttrList = new Dictionary<string, List<ClientAPIEntity>>();
        var m_AttrChild = new List<ClientAPIEntity>();
        var index = -1;
        foreach (DataRow row in dt.Rows)
        {
            if (row["Userattributename"].ToString().Equals("订单类别"))
            {
                continue;
            }
            addAttribute(ref m_AttrChild, dataEntity, row["Userattributename"].ToString(), row["AttributeValue"].ToString());
            index += 1;
            m_AttrList.Add(index.ToString(), m_AttrChild);
        }
        if (!string.IsNullOrWhiteSpace(para["AttributeValue"]))
        {
            addAttribute(ref m_AttrChild, dataEntity, "订单类别", para["AttributeValue"]);
            index += 1;
            m_AttrList.Add(index.ToString(), m_AttrChild);
        }
        var api = new External.APICalling.CamstarClientAPI(m_UserInfo.APIUserName.ToString(), m_UserInfo.APIPassword.ToString());
        var strInfo = string.Empty;
        return api.UpdateModelHasSubentityList("MfgOrderMaintDoc", "MfgOrderMaint", para["MfgOrderName"], "", "NDO", dataList, "Attributes", m_AttrList, dt.Rows.Count, ref strInfo);
    }

    private void addAttribute(ref List<ClientAPIEntity> childList, ClientAPIEntity dataEntity, string name, string value)
    {
        childList = new List<ClientAPIEntity>();
        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "Name";
        dataEntity.ClientDataValue = name;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);

        dataEntity = new ClientAPIEntity(); ;
        dataEntity.ClientDataName = "AttributeValue";
        dataEntity.ClientDataValue = value;
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "IsExpression";
        dataEntity.ClientDataValue = "false";
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);

        dataEntity = new ClientAPIEntity();
        dataEntity.ClientDataName = "DataType";
        dataEntity.ClientDataValue = "4";
        dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
        childList.Add(dataEntity);
    }

    //---------------订单分解-----------------

    private void GetMfgOrderSplitData(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        var strPid = string.Empty;
        var i_choose = 0;
        foreach (DataRow row in dt.Rows)
        {
            if (string.IsNullOrWhiteSpace(row["workflowid"].ToString()))
            {
                result.Message = "没有大阶段工艺!";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            if (!IsEixstpha(row["productname"].ToString(),row["workflowid"].ToString()))
            {
                result.Message = "请选择含有大阶段工艺的订单!";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            if (string.IsNullOrWhiteSpace(strPid))
            {
                strPid = row["ProductId"].ToString();
            }
            else
            {
                if (!strPid.Equals(row["ProductId"].ToString()))
                {
                    result.Message = "请选择相同件号!";
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
            }

            if (string.IsNullOrWhiteSpace(row["FactoryMonth"].ToString()))
            {
                result.Message = "订单" + row["MfgorderName"].ToString() + "请先维护计划!";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            //是否维护例行试验计划，发动机号和物料号是否和例行试验计划的一致
            DataTable RTPlanDt = m_CommonObj.GetTableInfo("ROUTINETESTRECORDplan", "Engineno", row["EngineNo"].ToString());
            if (RTPlanDt.Rows.Count > 0)
            {
                DataRow[] drs = RTPlanDt.Select("Routinetestrecordplanyear=" + DateTime.Now.Year.ToString());
                if (drs.Length > 0)
                {
                    if (drs[0]["Engineproductname"].ToString().Equals(row["ProductName"].ToString()))
                    {
                        result.Message = "发动机：" + row["EngineNo"].ToString() + "在" + DateTime.Now.Year.ToString() + "年，已维护例行试验计划，且物料号是" + drs[0]["Engineproductname"].ToString() + ",与要订单分解的记录不一致，禁止分解！";
                        context.Response.Write(JsonConvert.SerializeObject(result));
                        return;
                    }
                }

            }
            i_choose = i_choose + 1;
        }
        if (i_choose > 1 && argPara["ddlOrderStatus"].Equals("2"))
        {
            result.Message = "已分解订单请选单个调整!";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //result=GetMfgMergeData(context,dt.Rows[0]);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private Boolean IsEixstpha(string productname, string workflowid)
    {
        //'判断订单大阶段工艺--工序下--是否关联部件工艺（用来区分订单是否为无阶段订单）
        String strsqlEixst = @"SELECT COUNT(1) CH FROM (
                        SELECT count(wf.WORKFLOWREVISION) CN,ws.WORKFLOWSTEPNAME 
                        FROM WORKFLOWSTEP ws
                        LEFT JOIN workflow wf on INSTR(wf.phasenode,SUBSTR(ws.workflowstepname,INSTR(ws.workflowstepname,'-')+1))>0 AND splitandcheck(wf.LY2MODLE_NODE,'{0}',';')>0 --AND wf.LY2MODLE_NODE ='{0}'
                        WHERE ws.WORKFLOWID ='{1}' GROUP BY ws.WORKFLOWSTEPNAME 
                        ) WHERE cn>0";
        DataTable dtt = DatabaseHelper.Query_ReturnDatTable(String.Format(strsqlEixst, productname, workflowid));
        if (dtt.Rows.Count > 0)
            return Convert.ToInt32(dtt.Rows[0]["CH"]) > 0;
        else
        {
            return false;
        }
    }
    private uMESProcessResult GetMfgMergeData(HttpContext context, DataRow row)
    {
        var result = new uMESProcessResult();
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        if (row == null)
        {
            row = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString()).Rows[0];
        }
        var dict = new Dictionary<string, string>();
        dict.Add("ProductId", row["ProductId"].ToString());
        dict.Add("ProductName", row["ProductName"].ToString());
        dict.Add("MfgOrderId", row["MfgOrderId"].ToString());
        dict.Add("ProductFamilyid", row["ProductFamilyid"].ToString());
        dict.Add("StartDate", row["FactoryStarDate"].ToString());
        dict.Add("EngineNo", row["EngineNo"].ToString());
        dict.Add("workflowId", row["workflowId"].ToString());
        DataSet dsSession = m_PartPlanObj.SaveMfgOrderSession(dict);
        var para = new Dictionary<string, string>();
        para.Add("ProductId", row["ProductId"].ToString());
        DataTable Templet = m_PartPlanObj.GetMfgTemplet(para).Tables["Templet"];
        para = new Dictionary<string, string>();
        para.Add("MfgOrderId", row["MfgOrderId"].ToString());
        DataTable STemplet = m_PartPlanObj.GetMfgTemplet(para).Tables["Templet"];
        //设置选择项
        bool isExist = m_PartPlanObj.boolMfgOrderCreate(row["MfgOrderId"].ToString());//是否为已分解订单
        bool isTemplet = boolApplyTemplet(argPara);//'是否应用订单模板
        dsSession.Tables["dtMerge"].Columns.Add("ckSelect");

        foreach (DataRow dr in dsSession.Tables["dtMerge"].Rows)
        {
            if (isExist)
            {
                dr["ckSelect"] = dr["ExistFlag"].Equals("1") ? true : (dr["addDel"].Equals("1") ? true : false);
            }
            else
            {
                if (isTemplet)
                {
                    dr["ckSelect"] = dr["ExistFlag"].Equals("1") ? true : (dr["addDel"].Equals("1") ? true : false);
                }
                else
                {
                    dr["ckSelect"] = true;
                }
            }
            if (dr["ExistFlag"].Equals("C")) { dr["ckSelect"] = false; }
        }

        foreach (DataRow stepRow in dsSession.Tables["dtMfgStep"].Rows)
        {
            if (stepRow["SEQUENCE"].ToString().Equals("1"))
            {
                var FactoryStarDate = Convert.ToDateTime(row["FactoryStarDate"].ToString()).ToString("yyyy-MM-dd");
                var plannedStartDate = Convert.ToDateTime(stepRow["PLANNEDSTARTDATE"].ToString()).ToString("yyyy-MM-dd");
                if (!FactoryStarDate.Equals(plannedStartDate))
                {
                    stepRow["PLANNEDSTARTDATE"] = Convert.ToDateTime(FactoryStarDate);
                }
            }
            else
            {
                break;
            }
        }
        result.DBDataSet = dsSession;
        result.DBTable = Templet;
        result.ReturnData = STemplet;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
        return result;
    }

    private void GetBomListbyWorkflowid(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("Pid", argPara["PRODUCTID"]);
        para.Add("WorkFlowId", argPara["WORKFLOWID"]);
        para.Add("WorkFlowStepId", argPara["WORKFLOWSTEPID"]);
        para.Add("WorkFlowStepName", argPara["WORKFLOWSTEPNAME"]);
        para.Add("MfgOrderId", argPara["MFGORDERID"]);
        DataTable dt = m_PartPlanObj.GetProductWorkFlow(para);//部件所有工艺版本
        DataTable dtBom = m_PartPlanObj.GetBomListbyWorkflowid(para["WorkFlowId"]);//部件工艺bom数据
        if (dtBom.Rows.Count > 0)
        {
            dtBom = dtBom.Rows.Cast<DataRow>().OrderBy(r => r["BOMNAME"]).OrderBy(r => r["CHILDPRODUCTNAME"]).CopyToDataTable();
        }
        result.DBTable = dtBom;
        result.ReturnData = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void SaveTemplet(HttpContext context)
    {
        var result = new uMESProcessResult();
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var paraTemplet = new Dictionary<string, string>();
        paraTemplet.Add("TempletName", argPara["txtTempletName"]);
        if (argPara["txtTempletName"].Equals(argPara["ddlTemplet"]))
        {
            DataSet ds = m_PartPlanObj.GetMfgTemplet(paraTemplet);
            if (ds.Tables["Templet"].Rows.Count > 0)
            {
                result.Message = "模板名称已经存在";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        if (string.IsNullOrWhiteSpace(argPara["ddlTemplet"]))
        {
            result.Result = m_PartPlanObj.CreateMfgTemplet(argPara["MfgorderId"], argPara["txtTempletName"]);
            result.Message = result.Result ? "模板创建成功" : "模板创建失败";
        }
        else
        {
            result.Result = m_PartPlanObj.updateMfgTemplet(argPara["txtTempletName"], argPara["ddlTemplet"]);
            result.Message = result.Result ? "模板修改成功" : "模板修改失败";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void ClearTemplet(HttpContext context)
    {
        var result = new uMESProcessResult();
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        result.Result = m_PartPlanObj.updateMfgTemplet(string.Empty, argPara["txtTempletName"]);
        result.Message = result.Result ? "模板清除成功" : "模板清除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void CalcContainerPlan(HttpContext context)
    {
        var argDT = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        DataTable dtSession = JsonConvert.DeserializeObject<DataTable>(context.Request["dt"].ToString());//大阶段工序及其下关联部件信息
        var result = new uMESProcessResult();
        var stepStarDate = new DateTime();
        Double double_day = 0;

        for (var j = 0; j < argDT.Rows.Count; j++)
        {
            DataRow row = argDT.Rows[j];
            if (!Double.TryParse(row["CYCLETIME"].ToString(), out double_day))
            {
                result.Message = row["WORKFLOWSTEPNAME"].ToString() + "阶段,请输入数字";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            if (!new Regex("^\\d+(.5)?0*$").IsMatch((double_day * 8).ToString()))
            {
                result.Message = row["WORKFLOWSTEPNAME"].ToString() + "阶段," + row["CYCLETIME"].ToString() + "乘以8=" + (double_day * 8).ToString() + ",未精确到小时或半小时";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            if (j == 0)
            {
                stepStarDate = DateTime.Parse(DateTime.Parse(row["plannedstartdate"].ToString()).ToString("yyyy-MM-dd 08:30"));
            }
            else
            {
                stepStarDate = DateTime.Parse(argDT.Rows[j - 1]["plannedfinishdate"].ToString());
                if (stepStarDate >= stepStarDate.Date.AddHours(17.5))
                {
                    stepStarDate = stepStarDate.AddDays(1).Date.AddHours(8.5);
                }
            }
            row["PlannedStartDate"] = stepStarDate;
            //var p = stepStarDate.ToString();
            var addDays = Math.Floor(double_day); //Convert.ToInt32(double_day);
            Double addHours = (double_day - addDays) * 8;
            if (addDays > 0 && stepStarDate.Equals(stepStarDate.Date.AddHours(8.5)))
            {
                addDays -= 1;
                addHours += 8;
            }

            Double hoursToCompelete = 0;//开始当天还有多少小时到17:30,不可能为0
            if (stepStarDate <= stepStarDate.Date.AddHours(12))
            {
                hoursToCompelete = (DateTime.Parse(stepStarDate.ToString("yyyy-MM-dd 17:30")) - stepStarDate).Hours - 1;
            }
            else
            {
                hoursToCompelete = (DateTime.Parse(stepStarDate.ToString("yyyy-MM-dd 17:30")) - stepStarDate).Hours;
            }

            Boolean isClearTime = false;
            if (addHours > hoursToCompelete)
            {
                addDays += 1;
                addHours = addHours - hoursToCompelete;
                isClearTime = true;
            }
            if (stepStarDate <= stepStarDate.Date.AddHours(12) && addHours > (stepStarDate.Date.AddHours(12) - stepStarDate).Hours)
            { //addHours>12点，追加一小时
                addHours += 1;
            }
            if (isClearTime)
            {
                row["plannedfinishdate"] = stepStarDate.AddDays(addDays).Date.AddHours(8.5 + addHours).ToString("yyyy-MM-dd HH:mm");
            }
            else
            {
                row["plannedfinishdate"] = stepStarDate.AddDays(addDays).AddHours(addHours).ToString("yyyy-MM-dd HH:mm");
            }
            //var pf = row["plannedfinishdate"].ToString();
            if (DateTime.Parse(row["plannedfinishdate"].ToString()) > DateTime.Parse(row["plannedfinishdate"].ToString()).AddHours(17.5))
            {
                result.Message = "时间计算异常";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        DataTable dtt = CalcMfgOrderSession(argDT, dtSession);//根据大阶段调整结果，更新大阶段及其下关联部件的周期，开始/结束时间
        result.Result = true;
        result.DBTable = argDT;//大阶段时间
        result.ReturnData = dtt;//部件时间
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private DataTable CalcMfgOrderSession(DataTable dtMfgStep, DataTable dtSession) //dtMfgStep--大阶段周期调整后的时间信息
    {
        //DataTable dtSession = JsonConvert.DeserializeObject<DataTable>(context.Request["dt"].ToString());//大阶段工序及其下关联部件信息
        //DataTable dtwg = JsonConvert.DeserializeObject<DataTable>(context.Request["wg"].ToString());//大阶段-周期修改前的信息
        string CycleText = string.Empty;
        //DataRow drMfgStep = null;
        foreach (DataRow row in dtMfgStep.Rows)
        {
            DataRow[] drs = dtSession.Select(String.Format("workflowstepid='{0}'", row["workflowstepid"].ToString()));
            for (var i = 0; i < drs.Length; i++)
            {
                //执行过手动调整的不操作
                if (drs[i]["updateFlag"].ToString().Equals("1") && !string.IsNullOrWhiteSpace(drs[i]["plannedstartdate"].ToString()))
                {
                    continue;
                }
                if (drs[i]["existflag"].ToString().Equals("1"))
                {
                    //判断是否是大阶段调整,此判断为真正的大阶段调整
                    if (DateTime.Parse(drs[i]["plannedfinishdate"].ToString()) != DateTime.Parse(row["plannedfinishdate"].ToString()))
                    {
                        drs[i]["updateFlag"] = "2";
                    }
                    if (drs[i]["updateFlag"].ToString().Equals("0") && drs[i]["addDel"].ToString().Equals("0") && (drs[i]["CycleTime"].ToString() != row["CycleTime"] || (drs[i]["plannedstartdate"] != row["plannedstartdate"])))
                    {
                        continue;//此为之前手动调整过的批次
                    }
                }
                drs[i]["plannedstartdate"] = row["plannedstartdate"];
                drs[i]["plannedfinishdate"] = row["plannedfinishdate"];
                drs[i]["CycleTime"] = row["CycleTime"];//Convert.ToDecimal(CycleText);
            }
        }
        return dtSession;
        //foreach (DataRow row in dtwg.Rows)
        //{
        //    CycleText = row["cycletime"].ToString();
        //    DataRow[] drs = dtSession.Select(String.Format("workflowstepid='{0}'", row["workflowstepid"].ToString()));
        //    DataRow[] drMfgSteps = dtMfgStep.Select(String.Format(" workflowstepid='{0}'", row["workflowstepid"].ToString()));
        //    if (drMfgSteps.Length > 0) { drMfgStep = drMfgSteps[0]; }
        //    for (var i = 0; i < drs.Length;i++ ) {
        //        //执行过手动调整的不操作
        //        if (drs[i]["updateFlag"].ToString().Equals("1") && !string.IsNullOrWhiteSpace(drs[i]["plannedstartdate"].ToString()))
        //        {
        //            continue;
        //        }
        //        if (drs[i]["existflag"].ToString().Equals("1")) { 
        //            //判断是否是大阶段调整,此判断为真正的大阶段调整
        //            if (!drMfgStep["CycleTime"].Equals(CycleText) || (DateTime.Parse(drMfgStep["plannedstartdate"].ToString()) != DateTime.Parse(row["plannedstartdate"].ToString())))
        //            {
        //                drs[i]["updateFlag"] = "2";
        //            }
        //           if (drs[i]["updateFlag"].ToString().Equals("0") && drs[i]["addDel"].ToString().Equals("0")&& (drs[i]["CycleTime"].ToString()!=drMfgStep["CycleTime"] || (drs[i]["plannedstartdate"] != drMfgStep["plannedstartdate"])))
        //            {
        //                continue;//此为之前手动调整过的批次
        //            }
        //        }
        //        drs[i]["plannedstartdate"] = drMfgStep["plannedstartdate"];
        //        drs[i]["plannedfinishdate"] = drMfgStep["plannedfinishdate"];
        //        drs[i]["CycleTime"] = drMfgStep["CycleTime"];//Convert.ToDecimal(CycleText);
        //    }
        //}
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="orderRow">订单信息</param>
    /// <param name="firstOrderdtMerge">第一个订单件号对应的大阶段周期信息</param>
    /// <returns></returns>
    private DataTable CalcMfgOrder(DataRow orderRow, DataTable firstOrderdtMerge)
    {
        var dict = new Dictionary<string, string>();
        dict.Add("ProductId", orderRow["ProductId"].ToString());
        dict.Add("ProductName", orderRow["ProductName"].ToString());
        dict.Add("MfgOrderId", orderRow["MfgOrderId"].ToString());
        dict.Add("ProductFamilyid", orderRow["ProductFamilyid"].ToString());
        dict.Add("StartDate", orderRow["FactoryStarDate"].ToString());
        dict.Add("EngineNo", orderRow["EngineNo"].ToString());
        dict.Add("workflowId", orderRow["workflowId"].ToString());
        DataSet dsSession = m_PartPlanObj.SaveMfgOrderSession(dict);
        //-----------1.根据订单获取对应件号大阶段工艺信息、并计算各大阶段的开始、结束时间------------------
        DataTable argDT = dsSession.Tables["dtMfgStep"];
        var stepStarDate = new DateTime();
        Double double_day = 0;
        for (var j = 0; j < argDT.Rows.Count; j++)
        {
            DataRow row = argDT.Rows[j];
            DataRow[] firstOrderdtMergeDr = firstOrderdtMerge.Select(String.Format("workflowstepid='{0}'", row["workflowstepid"].ToString()));
            if (firstOrderdtMergeDr.Length > 0)
            {
                Double.TryParse(firstOrderdtMergeDr[0]["CYCLETIME"].ToString(), out double_day);
            }
            else { continue; }

            if (j == 0)
            {
                stepStarDate = DateTime.Parse(DateTime.Parse(orderRow["FactoryStarDate"].ToString()).ToString("yyyy-MM-dd 08:30"));//大阶段第一个序的开始时间取 订单分厂设置的开始时间
            }
            else
            {
                stepStarDate = DateTime.Parse(argDT.Rows[j - 1]["plannedfinishdate"].ToString());
                if (stepStarDate >= stepStarDate.Date.AddHours(17.5))
                {
                    stepStarDate = stepStarDate.AddDays(1).Date.AddHours(8.5);
                }
            }
            row["PlannedStartDate"] = stepStarDate;
            //var p = stepStarDate.ToString();
            var addDays = Math.Floor(double_day); //Convert.ToInt32(double_day);
            Double addHours = (double_day - addDays) * 8;
            if (addDays > 0 && stepStarDate.Equals(stepStarDate.Date.AddHours(8.5)))
            {
                addDays -= 1;
                addHours += 8;
            }

            Double hoursToCompelete = 0;//开始当天还有多少小时到17:30,不可能为0
            if (stepStarDate <= stepStarDate.Date.AddHours(12))
            {
                hoursToCompelete = (DateTime.Parse(stepStarDate.ToString("yyyy-MM-dd 17:30")) - stepStarDate).Hours - 1;
            }
            else
            {
                hoursToCompelete = (DateTime.Parse(stepStarDate.ToString("yyyy-MM-dd 17:30")) - stepStarDate).Hours;
            }

            Boolean isClearTime = false;
            if (addHours > hoursToCompelete)
            {
                addDays += 1;
                addHours = addHours - hoursToCompelete;
                isClearTime = true;
            }
            if (stepStarDate <= stepStarDate.Date.AddHours(12) && addHours > (stepStarDate.Date.AddHours(12) - stepStarDate).Hours)
            { //addHours>12点，追加一小时
                addHours += 1;
            }
            if (isClearTime)
            {
                row["plannedfinishdate"] = stepStarDate.AddDays(addDays).Date.AddHours(8.5 + addHours).ToString("yyyy-MM-dd HH:mm");
            }
            else
            {
                row["plannedfinishdate"] = stepStarDate.AddDays(addDays).AddHours(addHours).ToString("yyyy-MM-dd HH:mm");
            }
            row["cycletime"] = double_day;
            //var pf = row["plannedfinishdate"].ToString();
        }
        //--------------2.根据大阶段调整结果，更新大阶段及其下关联部件的周期，开始/结束时间-------------
        DataTable dtt = CalcMfgOrderSession(argDT, dsSession.Tables["dtMerge"]);//
        if (!dtt.Columns.Contains("isroutinetest")) { dtt.Columns.Add("isroutinetest"); }
        if (!dtt.Columns.Contains("CompleteStepId")) { dtt.Columns.Add("CompleteStepId"); }
        return dtt;
    }

    /// <summary>
    /// 订单应用
    /// </summary>
    /// <param name="context"></param>
    private void SaveSessionToDB(HttpContext context)
    {
        var flag = context.Request["flag"].ToString();
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["dt"].ToString());//待分解订单列表
        var wg = JsonConvert.DeserializeObject<DataTable>(context.Request["wg"].ToString());//当前订单大阶段工序信息
        var dtMerge = JsonConvert.DeserializeObject<DataTable>(context.Request["dtMerge"].ToString());//大阶段部件及其下挂的部件信息
        var result = new uMESProcessResult();
        if (!dtMerge.Columns.Contains("isroutinetest")) { dtMerge.Columns.Add("isroutinetest"); }
        if (!dtMerge.Columns.Contains("CompleteStepId")) { dtMerge.Columns.Add("CompleteStepId"); }

        Boolean isTemplet = boolApplyTemplet(argPara); //是否应用订单模板
        Boolean isExist = m_PartPlanObj.boolMfgOrderCreate(argPara["MfgOrderId"].ToString());//是否为已分解订单
        string ProductFamilyId = dt.Rows[0]["ProductFamilyId"].ToString();

        string msg = string.Empty;
        if (isTemplet && isExist)
        {
            if (m_PartPlanObj.ContainerHasExists(dt.Rows[0]["MfgOrderId"].ToString(), ref msg))
            {
                result.Message = "任务单已生成，不允许更改模板";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            else
            {
                //未生成任务单，删除重新分解
                var paraMfg = new Dictionary<string, object>();
                paraMfg["MfgOrderId"] = dt.Rows[0]["MfgOrderId"].ToString();
                m_PartPlanObj.DeleteEnginePartPlan(paraMfg);
            }
        }

        string cycletime = string.Empty;
        string startDate = string.Empty;
        string finishDate = string.Empty;
        var orderCount = 0;
        var SQLTransList = new List<object[]>();
        foreach (DataRow dr in dt.Rows)
        {
            var para = new Dictionary<string, object>();
            para.Add("Note", String.Empty);
            para.Add("MfgOrderID", dr["MfgOrderID"].ToString());
            para.Add("EmployeeID", m_UserInfo.EmployeeID);
            para.Add("TempletName", argPara["TempletName"]);
            SQLTransList.Clear();
            //DateTime PlannedStartDate_0 = DateTime.Parse(wg.Rows[0]["PlannedStartDate"].ToString());//当前订单大阶段分厂计划开始时间
            //DateTime PlannedStartDate_Now = DateTime.Parse(dr["FactoryStarDate"].ToString());//所选待分解订单分厂开始时间
            //全部订单应用
            if (flag.Equals("All") && dt.Rows.Count > 1 && orderCount > 0)
            {
                dtMerge = CalcMfgOrder(dr, wg);
            }


            var routineTestPara = new Dictionary<string, string>();
            routineTestPara.Add("EngineNo", dr["EngineNo"].ToString());
            routineTestPara.Add("RoutineTestPlanYear", DateTime.Now.Year.ToString());
            DataTable routineTestDT = m_RoutineTestObj.GetRoutineTestPlanInfo(routineTestPara);
            //------------------------------------------- 
            DataRow[] _dtMergeSession = dtMerge.Select("mfgorderid='" + dr["mfgorderid"].ToString() + "'");
            if (isTemplet) { _dtMergeSession = dtMerge.Select(); }
            foreach (DataRow drMerge in _dtMergeSession)
            {
                drMerge["CompleteStepId"] = m_PartPlanObj.GetCompleteStepID(drMerge["ProductID"].ToString(), drMerge["WorkflowID"].ToString());
                //处理例行试验的记录
                DataRow[] _dtMergeRows = dtMerge.Select("enginepartplanid is null");
                if (isTemplet) { _dtMergeRows = dtMerge.Select(); }
                if (_dtMergeRows.Length == 0)
                {
                    continue;
                }

                var _dtMerge = _dtMergeRows.CopyToDataTable();
                _dtMerge = _dtMerge.DefaultView.ToTable(true, "Phasenode", "Workflowname");
                foreach (DataRow _dtMergeRow in _dtMerge.Rows)
                {
                    var strCond = String.Format("phasenode='{0}' and partsworkflowname='{1}'", _dtMergeRow["Phasenode"], _dtMergeRow["Workflowname"]);
                    if (routineTestDT.Select(strCond).Length == 0) continue;

                    strCond = String.Format("enginepartplanid is null and phasenode='{0}' and workflowname='{1}'", _dtMergeRow["Phasenode"], _dtMergeRow["Workflowname"]);
                    //有例行试验计划
                    DataRow[] dtMergeRows = dtMerge.Select(strCond);
                    foreach (DataRow dtMergeRow in dtMergeRows)
                    {
                        dtMergeRow["isroutinetest"] = 1;
                    }
                }

                //判断是否需要填充ContainerName,如果workflowstepid 属于 workflowid 不需填充，否则需要填充
                if (drMerge["WorkflowID"].Equals(drMerge["wfid"]))
                {
                    drMerge["ContainerName"] = String.Empty;
                    drMerge["ContainerNO"] = String.Empty;
                }
                else
                {
                    //如果是资料库已经分解过的订单记录，不需要重新生成ContainerName
                    if (isTemplet || !drMerge["existFlag"].ToString().Equals("1"))
                    {
                        string str_Prefix = String.Format("{0}/JD{1}", drMerge["ProductName"], DateTime.Now.Year.ToString().Substring(2, 2));
                        string obj_Index = dtMerge.Compute("MAX(ContainerName)", String.Format("ContainerName like'{0}%'", str_Prefix)).ToString();
                        int max_Index = 0;
                        if (string.IsNullOrWhiteSpace(obj_Index))
                        {
                            max_Index = m_CommonObj.GetNewContainerPlanNextIndex(str_Prefix, 4);
                        }
                        else
                        {
                            int.TryParse(obj_Index.Replace(str_Prefix, String.Empty), out max_Index);
                            //二次验证
                            var conditionPara = new Dictionary<string, string>();
                            conditionPara["containername"] = String.Format("'{0}'", String.Format("{0}{1:D4}", str_Prefix, max_Index + 1));
                            DataTable concheckdt = m_CommonObj.GetTableInfoByField("enginepartplan", conditionPara, null);
                            if (concheckdt.Rows.Count > 0)// '已存在)
                            {
                                max_Index = m_CommonObj.GetNewContainerPlanNextIndex(str_Prefix, 4);
                            }
                        }
                        drMerge["ContainerName"] = String.Format("{0}{1:D4}", str_Prefix, max_Index + 1);//
                    }
                    drMerge["ContainerNO"] = String.Format("{0}-{1}", dr["EngineNo"].ToString(), drMerge["ProductName"]);//发动机号--件号
                }
                dtMerge.AcceptChanges();
            }
            //----------------------------------------------
            foreach (DataRow drMerge in _dtMergeSession)
            {
                para["ProductID"] = drMerge["ProductID"].ToString();
                para["WorkflowID"] = drMerge["WorkflowID"].ToString();
                para["mProductID"] = dr["ProductId"].ToString();
                //获取集成的工区
                para["WorkCenterId"] = string.IsNullOrWhiteSpace(drMerge["ContainerNo"].ToString()) ? "" : m_PartPlanObj.GetNearestWorkCenter(para);
                //完工工序记录
                para["CompleteStepId"] = string.IsNullOrWhiteSpace(drMerge["CompleteStepId"].ToString()) ? String.Empty : drMerge["CompleteStepId"].ToString();
                para["IsRoutineTest"] = string.IsNullOrWhiteSpace(drMerge["IsRoutineTest"].ToString()) ? "0" : drMerge["IsRoutineTest"].ToString();
                para["WorkflowStepID"] = drMerge["WorkflowStepID"].ToString();
                para["WorkflowStepName"] = drMerge["WorkflowStepName"].ToString();
                if (!string.IsNullOrWhiteSpace(drMerge["plannedstartdate"].ToString()))
                {
                    startDate = drMerge["plannedstartdate"].ToString();
                    finishDate = drMerge["plannedfinishdate"].ToString();
                    cycletime = drMerge["CycleTime"].ToString();
                }

                para["PlannedStartDate"] = DateTime.Parse(startDate);
                para["PlannedFinishDate"] = DateTime.Parse(finishDate);
                para["CycleTime"] = cycletime;
                para["ProductFamilyId"] = ProductFamilyId;
                para["EngineContainerID"] = String.Empty;
                para["ContainerID"] = String.Empty;
                para["ContainerName"] = drMerge["ContainerName"].ToString();
                para["TOGETHERFLAG"] = drMerge["ContainerNO"].ToString();

                if (isTemplet)
                {
                    if (drMerge["addDel"].ToString().Equals("C")) continue;//如果没有勾选，不用创建
                    //应用了模板，但此记录不为模板创建的批次且没有点选
                    if (drMerge["existFlag"].ToString().Equals("0") & drMerge["addDel"].ToString().Equals("0") & drMerge["updateFlag"].ToString().Equals("0")) continue;
                    SQLTransList.Add(m_PartPlanObj.FillSaveEnginePartPlan(para));//----------参数组装【EnginePartPlan】SQL---
                    if (dtMerge.Rows[dtMerge.Rows.Count - 1]["WorkflowStepID"].Equals(para["WorkflowStepID"]))
                    {
                        SQLTransList.Add(m_PartPlanObj.FillUpdateMfgFinishDate(para));//----------更新订单分厂完成日期------------
                    }
                }
                else
                {
                    if (drMerge["existFlag"].ToString().Equals("1"))
                    {
                        if (drMerge["addDel"].ToString().Equals("0") & drMerge["updateFlag"].ToString().Equals("0")) continue;//'如果是已经分解过的订单批次，对没有变更的记录不执行更改
                        if (drMerge["addDel"].ToString().Equals("C"))
                        {
                            // '如果是已经分解过的记录做此取消操作，需删除原来的记录
                            // '需要先检查批次是否创建
                            // '大阶段的不会删除，故删除的只能是有ContainerName的记录
                            if (m_PartPlanObj.boolEngineContainerExists(para["ContainerName"].ToString()))//如果存在，不执行删除操作
                            {
                                continue;
                            }
                            else//如果不存在
                            {
                                SQLTransList.Add(m_PartPlanObj.FillDeleteEnginePartPlan(para));
                            }
                        }
                        else
                        {
                            //'不为删除操作，如果为更改工艺或周期，开始时间
                            //'此处执行更新操作
                            if (drMerge["updateFlag"].ToString().Equals("1") | drMerge["updateFlag"].ToString().Equals("2"))
                            {
                                if (m_PartPlanObj.boolEngineContainerExists(para["ContainerName"].ToString()))
                                {
                                    //如果存在，不执行操作
                                    continue;
                                }
                                else
                                {
                                    SQLTransList.Add(m_PartPlanObj.FillUpdateEnginePartPlan(para));//如果不存在,如果为大阶段批次，没有containerName,单独的更新会出错
                                }
                            }
                        }
                    }
                    else
                    {
                        if (drMerge["addDel"].ToString().Equals("C")) continue;
                        if (isExist && drMerge["addDel"].ToString().Equals("0") & drMerge["updateFlag"].ToString().Equals("0")) continue;//'订单已分解的情况下，只处理需要更改的记录
                        SQLTransList.Add(m_PartPlanObj.FillSaveEnginePartPlan(para));//----------参数组装【EnginePartPlan】SQL---
                        if (dtMerge.Rows[dtMerge.Rows.Count - 1]["WorkflowStepID"].Equals(para["WorkflowStepID"]))
                        {
                            SQLTransList.Add(m_PartPlanObj.FillUpdateMfgFinishDate(para));//----------更新订单分厂完成日期------------
                        }
                    }
                }
            }
            //---------------------------
            if (SQLTransList.Count > 0)
            {
                if (!DatabaseHelper.ExecuteSqlTran(SQLTransList))
                {
                    result.Message = dr["MfgOrderName"].ToString() + " 分解失败";
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                m_PartPlanObj.InsertOrReplaceMfgEngine(dr);//插入mfg_engine_data，用于记录一个订单分解时使用的发动机件号和大阶段工艺
            }
            else
            {
                result.Message = " 无待分解订单";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            //增加分解后，判断是否成功
            if (m_PartPlanObj.GetSplitData(dr["MfgorderId"].ToString(), dr["ProductId"].ToString(), dr["workflowId"].ToString()))
            {
                result.Message = dr["MfgOrderName"].ToString() + "分解不成功,请重新分解";
                var paraDel = new Dictionary<String, Object>();
                paraDel["MfgOrderId"] = dr["MfgorderId"].ToString();
                m_PartPlanObj.DeleteEnginePartPlan(paraDel);//不成功、删除已分解记录
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }


            if (flag.Equals("One"))
            {//当前单个订单应用，跳出循环
                break;
            }
            orderCount = +1;
        }
        DatabaseHelper.ExecuteSql("BEGIN AUTO_EP_WFPRODUCT_DATA_SP();END;");
        result.Message = "分解成功";
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }



    /// <summary>
    /// 部件勾选或取消勾选
    /// </summary>
    /// <param name="context"></param>
    private void WgResultCheckChange(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());//选择的下拉订单
        var dtMerge = JsonConvert.DeserializeObject<DataTable>(context.Request["dtMerge"].ToString());//大阶段部件及其下挂的部件信息
        var argRow = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["row"].ToString());//勾选或取消的行
        var result = new uMESProcessResult();
        DataRow[] drs = dtMerge.Select(String.Format("WorkFlowStepId='{0}' and productid='{1}' and WorkflowId='{2}'", argRow["WORKFLOWSTEPID"].ToString(), argRow["PRODUCTID"].ToString(), argRow["WORKFLOWID"].ToString()));
        if (drs.Length == 0)
        {
            result.Message = "所选记录不存在";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataRow dr = drs[0];
        Boolean isExist = m_PartPlanObj.boolMfgOrderCreate(argPara["MfgOrderId"].ToString());//是否为已分解订单
        if (argRow["ckSelect"].Equals("True"))
        {
            dr["addDel"] = isExist ? (argRow["EXISTFLAG"].Equals("1") ? "0" : "1") : "1";
        }
        else
        {
            dr["addDel"] = "C";
        }
        dr["ckSelect"] = argRow["ckSelect"];
        result.ReturnData = dtMerge;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 是否应用订单模板
    /// </summary>
    /// <param name="mfgorderid"></param>
    /// <returns></returns>
    private bool boolApplyTemplet(Dictionary<string, string> dic)
    {
        bool boolApply = false;
        if (string.IsNullOrWhiteSpace(dic["TempletName"])) { return false; }
        var para = new Dictionary<string, string>();
        para["MfgOrderId"] = dic["MfgOrderId"];
        DataTable dtTemplet = m_PartPlanObj.GetMfgTemplet(para).Tables["Templet"];
        if (dtTemplet.Rows.Count > 0)
        {
            if (!dtTemplet.Rows[0]["templetname"].ToString().Equals(dic["MfgOrderId"]))
            {
                boolApply = true;
            }
        }
        else
        {
            boolApply = true;
        }
        return boolApply;
    }
    /// <summary>
    /// 部件工艺下拉选择
    /// </summary>
    /// <param name="context"></param>
    private void WorkFlowDataChange(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para["Pid"] = argPara["PRODUCTID"];
        para["WorkFlowId"] = argPara["DDWORKFLOWID"];
        para["WorkFlowStepId"] = argPara["WORKFLOWSTEPID"];
        para["WorkFlowStepName"] = argPara["WORKFLOWSTEPNAME"];
        para["MfgOrderId"] = argPara["MFGORDERID"];

        DataTable dt = m_PartPlanObj.GetProductWorkFlowCycletime(para);
        if (dt.Rows.Count > 0)
        {
            result.ReturnData = dt.Rows[0]["cycletime"].ToString();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 制定计划
    /// </summary>
    /// <param name="context"></param>
    private void SaveProductPlan(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var dtMerge = JsonConvert.DeserializeObject<DataTable>(context.Request["dtMerge"].ToString());//大阶段部件及其下挂的部件信息
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["dt"].ToString());//部件信息
        var result = new uMESProcessResult();
        DateTime StartDate = DateTime.Parse(argPara["txtfplanStartDate"]);//初始化开始日期 
        Double cycle = Double.Parse(argPara["txtCycle"]);//周期
        DateTime FinishDate;
        //计算完成日期
        int addDays = Convert.ToInt32(cycle);
        Double addHours = (cycle - addDays) * 8;
        if (addDays > 0)
        {
            addDays -= 1;
            addHours += 8;
            if (addHours > 8)
            {
                addHours = addHours - 8;
                addDays += 1;
            }
        }
        if (addHours > 3.5)
        {
            addHours += 1;
        }
        FinishDate = StartDate.AddDays(addDays).AddHours(addHours);
        if (FinishDate > DateTime.Parse(argPara["plannedfinishdate"]))
        {
            result.Message = "分厂计划完成日期晚于大阶段计划完成日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (DataRow row in dt.Rows)
        {
            if (row["ckSelect"].ToString().Equals("True"))
            {
                row["cycletime"] = cycle;
                row["plannedstartdate"] = StartDate;
                row["plannedfinishdate"] = FinishDate;
                //更新全局 dtMerge 对应部件新
                DataRow[] drs = dtMerge.Select(String.Format("workflowstepid='{0}' and productid='{1}' and workflowid='{2}'", row["workflowstepid"], row["productid"], row["workflowid"]));
                if (drs.Length > 0)
                {
                    DataRow dr = drs[0];
                    dr["cycletime"] = cycle;
                    dr["plannedstartdate"] = StartDate;
                    dr["plannedfinishdate"] = FinishDate;
                    dr["updateFlag"] = "1";
                }
            }
        }
        result.ReturnData = dtMerge;
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 调整工艺
    /// </summary>
    private void UpdateMergeWorkFlow(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var dtMerge = JsonConvert.DeserializeObject<DataTable>(context.Request["dtMerge"].ToString());//大阶段部件及其下挂的部件信息
        var row = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["row"].ToString());//部件选中行
        var result = new uMESProcessResult();

        DataRow[] drs = dtMerge.Select(String.Format("workflowstepid='{0}' and productid='{1}' and workflowid='{2}'", row["WORKFLOWSTEPID"], row["PRODUCTID"], row["WORKFLOWID"]));
        if (drs.Length > 0)
        {
            DataRow dr = drs[0];
            //更新工艺
            dr["Workflowid"] = argPara["WorkflowId"];
            dr["workflownamever"] = argPara["WorkflowName"];
            dr["workflowname"] = argPara["WorkflowName"].Substring(0, argPara["WorkflowName"].IndexOf(":"));
            dr["workflowrevision"] = argPara["WorkflowName"].Substring(argPara["WorkflowName"].IndexOf(":") + 1, argPara["WorkflowName"].ToString().Length - argPara["WorkflowName"].IndexOf(":") - 1);
            //计算日期
            dr["cycletime"] = argPara["txtCycle"];
            DateTime StartDate = DateTime.Parse(argPara["txtfplanStartDate"]).Date.AddHours(8.5);
            dr["plannedstartdate"] = StartDate;
            Double cycle = Double.Parse(argPara["txtCycle"]);
            if (!new Regex("^\\d+(.5)?0*$").IsMatch((cycle * 8).ToString()))
            {
                result.Message = row["CYCLETIME"].ToString() + "乘以8=" + (cycle * 8).ToString() + ",未精确到小时或半小时";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            int addDays = Convert.ToInt32(cycle);
            Double addHours = (cycle - addDays) * 8;
            if (addDays > 0)
            {
                addDays -= 1;
                addHours += 8;
                if (addHours > 8)
                {
                    addHours = addHours - 8;
                    addDays += 1;
                }
            }
            if (addHours > 3.5)
            {
                addHours += 1;
            }
            dr["plannedfinishdate"] = StartDate.AddDays(addDays).AddHours(addHours);
            //更新操作标示
            dr["updateFlag"] = "1";
        }
        result.ReturnData = dtMerge;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 施工单查询
    /// </summary>
    /// <param name="context"></param>
    private void GetSGDData(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("CurrentPageIndex", pageNumber);
        para.Add("PageSize", pageSize);
        para.Add("WorkflowName", argPara["txtWorkflowName"]);
        para.Add("EngineNO", argPara["txtEngineNO"]);
        para.Add("Status", argPara["ddlStatus"]);
        var result = m_CommonObj.GetTempWorkflow(para);//-----------------
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 施工单分解
    /// </summary>
    /// <param name="context"></param>
    private void SplitTempOrder(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());
        var dttemp = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        try
        {
            DataTable dt = m_PartPlanObj.GetTempOrderTable(argPara);
            if (!dt.Columns.Contains("EngineNo")) { dt.Columns.Add("EngineNo"); }
            //插入enginepartplan表
            //开批次
            foreach (DataRow dr in dt.Rows)
            {
                dr["factorycompletiondate"] = argPara["PlannedFinishDate"];
                dr["EngineNo"] = argPara["engineNo"];
                var msg = string.Empty;
                result.Result = SaveEnginePartPlanData(dr, "2", ref msg);
                if (!result.Result)
                {
                    result.Message = msg;
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                else
                {
                    DataRow drtemp = dttemp.Select(String.Format("mfgorderid='{0}'", dr["mfgorderid"]))[0];
                    drtemp["workflowid"] = "";
                    m_PartPlanObj.InsertOrReplaceMfgEngine(drtemp);
                    result.Message = "临时任务分解完成!";
                }
            }
        }
        catch (Exception ex) { result.Message = ex.Message; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 技通单查询（分页）
    /// </summary>
    /// <param name="context"></param>
    private void GetJTDData(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("CurrentPageIndex", pageNumber);
        para.Add("PageSize", pageSize);
        para.Add("WorkflowName", argPara["txtWorkflowName"]);
        para.Add("EngineNO", argPara["txtEngineNO"]);
        para.Add("MfgorderID", argPara["MfgOrderID"]);
        var result = m_RoutineTestObj.GetTechnicalWorkflowForSplit(para);//-----------------
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 技通单-确认
    /// </summary>
    /// <param name="context"></param>
    private void TechnicalWorkflowForSplit(HttpContext context)
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["fdata"].ToString());//参数
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());//勾选的技通单信息
        var wgRow = JsonConvert.DeserializeObject<DataTable>(context.Request["row"].ToString()).Rows[0];//勾选的单行订单信息
        var result = new uMESProcessResult();
        try
        {
            DataTable inserDt = new DataTable();
            inserDt.Columns.Add("mfgorderid");
            inserDt.Columns.Add("WorkflowName");
            inserDt.Columns.Add("WorkflowRevision");
            inserDt.Columns.Add("WorkflowID");
            inserDt.Columns.Add("productid");
            inserDt.Columns.Add("factorystardate");
            inserDt.Columns.Add("factorycompletiondate");
            inserDt.Columns.Add("MfgOrderName");
            inserDt.Columns.Add("ProductRevision");
            inserDt.Columns.Add("ProductName");
            inserDt.Columns.Add("EngineNo");
            DataRow dr = inserDt.Rows.Add(0);
            dr["mfgorderid"] = wgRow["MfgOrderID"].ToString();
            dr["mfgordername"] = wgRow["mfgordername"].ToString();
            dr["ProductID"] = wgRow["ProductID"].ToString();
            dr["ProductRevision"] = wgRow["ProductRevision"].ToString();
            dr["factorystardate"] = wgRow["factorystardate"].ToString();
            dr["ProductName"] = wgRow["ProductName"].ToString();
            dr["factorycompletiondate"] = argPara["PlannedFinishDate"].ToString();
            dr["EngineNo"] = wgRow["EngineNo"].ToString(); //'发动机号
            string msg = string.Empty;
            foreach (DataRow row in dt.Rows)
            {
                dr["WorkflowID"] = row["WorkflowID"].ToString();
                dr["WorkflowName"] = row["WorkflowName"].ToString();
                dr["WorkflowRevision"] = row["WorkflowRevision"].ToString();
                if (m_RoutineTestObj.GetMfgorderEnginePartPlanInfo(wgRow["MfgOrderID"].ToString(), row["WorkflowID"].ToString()).Rows.Count > 0)
                {
                    msg += "订单:" + dr["mfgordername"].ToString() + "已有技通单：" + dr["WorkflowName"].ToString() + "的分解记录;";
                    continue;
                }
                if (!SaveEnginePartPlanData(dr, "3", ref msg))
                {
                    result.Message = msg;
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                else
                {
                    DataRow drtemp = wgRow;
                    drtemp["workflowid"] = "";
                    m_PartPlanObj.InsertOrReplaceMfgEngine(drtemp);
                    result.Message = "临时任务分解完成!";
                }
            }
            result.Message = msg;
        }
        catch (Exception ex) { result.Message = ex.Message; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 分解无大阶段-子部件订单
    /// </summary>
    /// <param name="context"></param>
    /// 
    private void SplitNoMergeOrder(HttpContext context)
    {
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());//勾选的无大阶段订单信息
        var result = new uMESProcessResult();
        var IsNoMergeOrder = string.Empty;//判断是否都是无大阶段订单
        try
        {
            foreach (DataRow row in dt.Rows)
            {
                if (string.IsNullOrWhiteSpace(row["factorymonth"].ToString()) || string.IsNullOrWhiteSpace(row["factorystardate"].ToString()))
                {
                    result.Message = "请勾选【分厂计划月份/开始日期】已维护的无大阶段订单信息再进行操作";
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                if (IsEixstpha(row["productname"].ToString(), row["workflowid"].ToString()))//row["IsEixstpha"].ToString().Equals("1"))
                {
                    IsNoMergeOrder += row["workflowid"].ToString() + ",";
                }
            }
            if (!string.IsNullOrWhiteSpace(IsNoMergeOrder))
            {
                result.Message = "请勾选相同无大阶段订单信息再进行操作";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }

            var SQLTransList = new List<object[]>();
            foreach (DataRow dr in dt.Rows)
            {
                var para = new Dictionary<string, object>();
                para.Add("Note", String.Empty);
                para.Add("MfgOrderID", dr["MfgOrderID"].ToString());
                para.Add("EmployeeID", m_UserInfo.EmployeeID);
                para.Add("TempletName", "");
                SQLTransList.Clear();

                para["ProductID"] = dr["ProductID"].ToString();//drMerge
                para["WorkflowID"] = dr["WorkflowID"].ToString();//drMerge
                para["mProductID"] = dr["ProductId"].ToString();
                //获取集成的工区
                para["WorkCenterId"] = m_PartPlanObj.GetNearestWorkCenter(para);
                //完工工序记录
                para["CompleteStepId"] = String.Empty;
                para["IsRoutineTest"] = "0";
                para["WorkflowStepID"] = dr["WorkflowID"].ToString();//无阶段部件--工序ID默认使用工艺ID
                para["WorkflowStepName"] = string.Empty;
                para["PlannedStartDate"] = DateTime.Parse(dr["factorystardate"].ToString());
                para["PlannedFinishDate"] = DateTime.Parse(dr["PLANNEDCOMPLETIONDATE"].ToString());
                para["CycleTime"] = 0;
                para["ProductFamilyId"] = dr["ProductFamilyId"].ToString(); ;
                para["EngineContainerID"] = String.Empty;
                para["ContainerID"] = String.Empty; //Guid.NewGuid().ToString();
                para["ContainerName"] = dr["EngineNo"].ToString() + "-" + dr["workflowname"].ToString();//批次名称(发动机号-工艺名称)
                para["TOGETHERFLAG"] = dr["EngineNo"].ToString() + "/" + dr["workflowname"].ToString();//大批次名称(发动机号/工艺名称)
                SQLTransList.Add(m_PartPlanObj.FillSaveEnginePartPlan(para));
            }

            if (SQLTransList.Count > 0)
            {
                result.Result = DatabaseHelper.ExecuteSqlTran(SQLTransList);
                result.Message = result.Result ? "分解成功" : " 分解失败";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            else
            {
                result.Message = " 无待分解订单";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        catch (Exception ex) { result.Message = ex.Message; }
        context.Response.Write(JsonConvert.SerializeObject(result));

    }


    private void SplitNoMergeOrder2(HttpContext context)
    {
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());//勾选的无大阶段订单信息
        var result = new uMESProcessResult();
        var IsNoMergeOrder = string.Empty;//判断是否都是无大阶段订单
        try
        {
            foreach (DataRow row in dt.Rows)
            {
                if (string.IsNullOrWhiteSpace(row["factorymonth"].ToString()) || string.IsNullOrWhiteSpace(row["factorystardate"].ToString()))
                {
                    result.Message = "请勾选【分厂计划月份/开始日期】已维护的无大阶段订单信息再进行操作";
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                if (row["IsEixstpha"].ToString().Equals("1"))
                {
                    IsNoMergeOrder += row["workflowid"].ToString() + ",";
                }
            }
            if (!string.IsNullOrWhiteSpace(IsNoMergeOrder))
            {
                result.Message = "请勾选相同无大阶段订单信息再进行操作";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            DataTable inserDt = new DataTable();
            inserDt.Columns.Add("mfgorderid");
            inserDt.Columns.Add("WorkflowName");
            inserDt.Columns.Add("WorkflowRevision");
            inserDt.Columns.Add("WorkflowID");
            inserDt.Columns.Add("productid");
            inserDt.Columns.Add("factorystardate");
            inserDt.Columns.Add("factorycompletiondate");
            inserDt.Columns.Add("MfgOrderName");
            inserDt.Columns.Add("ProductRevision");
            inserDt.Columns.Add("ProductName");
            inserDt.Columns.Add("EngineNo");
            string msg = string.Empty;
            foreach (DataRow row in dt.Rows)
            {
                DataRow dr = inserDt.Rows.Add(0);
                dr["mfgorderid"] = row["MfgOrderID"].ToString();//任务单【订单】ID
                dr["mfgordername"] = row["mfgordername"].ToString();//任务单【订单名称】
                dr["ProductID"] = row["ProductID"].ToString();//订单件号ID
                dr["ProductRevision"] = row["ProductRevision"].ToString();//订单件号版次
                dr["factorystardate"] = row["factorystardate"].ToString();//分厂计划开始时间
                dr["ProductName"] = row["ProductName"].ToString();//订单件号名称（描述）
                dr["factorycompletiondate"] = row["PLANNEDCOMPLETIONDATE"].ToString();//分厂计划完成时间--factorycompletiondate
                dr["EngineNo"] = row["EngineNo"].ToString(); //'发动机号
                dr["WorkflowID"] = row["WorkflowID"].ToString();//订单件号默认版本工艺ID
                dr["WorkflowName"] = row["WorkflowName"].ToString();//订单件号默认版本工艺名称
                dr["WorkflowRevision"] = row["WorkflowRevision"].ToString();//订单件号默认版本工艺版本
                if (!SaveEnginePartPlanData(dr, "1", ref msg))
                {
                    result.Message = msg;
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                else
                {
                    DataRow drtemp = row;
                    drtemp["workflowid"] = "";
                    m_PartPlanObj.InsertOrReplaceMfgEngine(drtemp);
                    result.Message = "无大阶段订单任务分解完成!";
                }
            }

        }
        catch (Exception ex) { result.Message = ex.Message; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }


    private Boolean SaveEnginePartPlanData(DataRow dr, string type, ref string msg)
    {
        bool result = false;
        var para = new Dictionary<string, object>();
        para.Add("Note", String.Empty);//备注
        para.Add("MfgOrderID", dr["MfgOrderID"].ToString());//所属生产订单ID
        para.Add("EmployeeID", m_UserInfo.EmployeeID);//开卡人ID
        para["TempletName"] = String.Empty;//
        para["ProductID"] = dr["ProductID"].ToString();//零部件ID(件号ID)
        para["WorkflowID"] = dr["WorkflowID"].ToString();//所使用工艺路线ID
        para["WorkflowStepID"] = String.Empty;
        para["PlannedStartDate"] = string.IsNullOrWhiteSpace(dr["factorystardate"].ToString()) ? DateTime.Now.ToShortDateString() : DateTime.Parse(dr["factorystardate"].ToString()).ToShortDateString();
        para["PlannedFinishDate"] = DateTime.Parse(dr["factorycompletiondate"].ToString()).ToShortDateString();// '时间设置为计划完成时间
        para["CycleTime"] = "0";//
        para["ProductFamilyId"] = String.Empty;
        para["EngineContainerID"] = String.Empty;
        para["ContainerID"] = String.Empty;
        para["ContainerName"] = dr["EngineNo"].ToString() + "-" + dr["workflowname"].ToString();//批次名称(发动机号-工艺名称)
        para["TOGETHERFLAG"] = dr["EngineNo"].ToString() + "/" + dr["workflowname"].ToString();//大批次名称(发动机号/工艺名称)
        para["MfgOrderName"] = dr["MfgOrderName"].ToString();//订单名称
        para["ProductName"] = string.IsNullOrWhiteSpace(dr["ProductName"].ToString()) ? String.Empty : dr["ProductName"].ToString();//零部件（件号）名称
        para["ProductRevision"] = string.IsNullOrWhiteSpace(dr["ProductRevision"].ToString()) ? String.Empty : dr["ProductRevision"].ToString();//零部件（件号）版次
        para["WorkflowName"] = dr["workflowname"].ToString();//工艺名称
        para["WorkflowRevision"] = dr["WorkflowRevision"].ToString();//工艺版本
        para["CompleteStepId"] = String.Empty;
        para["WorkCenterId"] = String.Empty;
        DataTable dt = m_CommonObj.GetWorkFlowSetpsByWorkflowID(para["WorkflowID"].ToString());
        if (dt.Select(" teamid is null").Length > 0 && type == "3")
        {
            msg = "分解失败，" + dr["workflowname"].ToString() + "有工序未分配小组";
        }
        if (m_ContainerObj.GetContainerData(para["ContainerName"].ToString()).Rows.Count > 0)
        {
            msg = "临时订单单号已有开卡";
        }
        para["EnginePartPlanType"] = type;
        //执行插入操作 EnginePartPlan
        if (m_PartPlanObj.SaveEnginePartPlanData(para))
        {
            string msg1 = string.Empty;
            result = StarContainer(para, ref msg1);//-----------开卡
            if (!result)
            {
                msg = "分解完成,开卡失败" + msg1;
            }
            else
            {
                //根据施工单工序指定的首道工序对应的班组，自动派工
                DataTable dtWfs = m_CommonObj.GetWorkFlowSetpsByWorkflowID(para["WorkflowID"].ToString());
                //施工单班长派工由派到首道工序对应组，改为每道工序单独派工（每道工序一条记录）
                if (dtWfs.Rows.Count > 0)
                {
                    DataView dv = dtWfs.DefaultView;
                    dv.RowFilter = "teamid is not null or workcenterid is not null";
                    dtWfs = dv.ToTable(true, "WORKFLOWSTEPNAME", "WORKFLOWSTEPID", "workcenterid", "teamid");
                    foreach (DataRow drW in dtWfs.Rows)
                    {
                        var dtShiftAndWc = new DataTable();
                        var ShiftId = string.Empty;
                        var TeamId = drW["teamid"].ToString();
                        var Workcenterid = drW["Workcenterid"].ToString();
                        if (!string.IsNullOrWhiteSpace(TeamId))
                        {
                            dtShiftAndWc = m_CommonObj.GetShiftAndWorkcenterByTeamid(TeamId);
                            ShiftId = dtShiftAndWc.Rows[0]["ShiftID"].ToString();
                        }
                        if (!string.IsNullOrWhiteSpace(Workcenterid))
                        {
                            dtShiftAndWc = m_CommonObj.GetWorkCenterInfoByWorkCenterID(Workcenterid);
                        }
                        ContainerTeamDispatchDTO dto = new ContainerTeamDispatchDTO();
                        dto.ContainerID = m_CommonObj.GetContainerInfobyContainerName(para["ContainerName"].ToString()).Rows[0]["containerid"].ToString();
                        dto.FactoryID = m_UserInfo.FactoryID;
                        dto.WorkCenterID = dtShiftAndWc.Rows[0]["workcenterid"].ToString();
                        dto.WorkflowstepID = drW["WORKFLOWSTEPID"].ToString();
                        dto.ContainerTeamDispatchID = Guid.NewGuid().ToString();
                        dto.EmployeeID = m_UserInfo.EmployeeID;
                        dto.TeamID = TeamId;
                        dto.ShiftID = ShiftId;
                        result = m_DispatchObj.AddContainerTeamDispatchInfo(dto);
                        msg = result ? "分解完成,自动派报工成功" : "分解完成,自动派报工失败";
                    }
                }
            }
        }
        else
        {
            msg = "分解异常";
        }
        return result;
    }

    private bool StarContainer(Dictionary<string, object> para, ref string msg)
    {
        var containerBaseInfo = new ContainerStartInfo();
        containerBaseInfo.ContainerName = para["ContainerName"];//批次名称
        containerBaseInfo.Qty = 1;
        containerBaseInfo.MfgOrder = para["MfgOrderName"];//所属生产订单
        containerBaseInfo.IsSelfMfg = 0;
        //FillContainerDefaultInfo(containerBaseInfo);
        containerBaseInfo.TogetherFlag = para["TOGETHERFLAG"];//大批次号
        containerBaseInfo.Factory = m_UserInfo.Factory;//分厂
        containerBaseInfo.StartEmployee = m_UserInfo.EmployeeName;//开卡人
        containerBaseInfo.ProductName = para["ProductName"];//零部件（件号）名称
        containerBaseInfo.ProductRevision = para["ProductRevision"];//零部件（件号）版本
        containerBaseInfo.ProductuseROR = false;
        containerBaseInfo.MfgWorkflowName = para["WorkflowName"];//
        containerBaseInfo.MfgWorkflowRevision = para["WorkflowRevision"];//
        containerBaseInfo.MfgWorkflowuseROR = false;
        containerBaseInfo.WorkflowName = para["WorkflowName"];//
        containerBaseInfo.WorkflowRevision = para["WorkflowRevision"];//
        containerBaseInfo.WorkflowuseROR = false;
        containerBaseInfo.PlannedStartDate = DateTime.Parse(para["PlannedStartDate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.PlannedCompletionDate = DateTime.Parse(para["PlannedFinishDate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.ContainerType = 7;
        containerBaseInfo.AttributeList = new DataTable();
        //填充批次默认信息
        var strOwner = string.Empty;
        var strLevel = string.Empty;
        var strStart = string.Empty;
        DataTable levelAttributes = m_CommonObj.GetFatoryAttributes(m_UserInfo.FactoryID);
        DataRow[] datarows = levelAttributes.Select("USERATTRIBUTENAME='默认所有者'");
        if (datarows.Length > 0) { strOwner = datarows[0]["ATTRIBUTEVALUE"].ToString(); }
        datarows = levelAttributes.Select("USERATTRIBUTENAME='默认层级'");
        if (datarows.Length > 0) { strLevel = datarows[0]["ATTRIBUTEVALUE"].ToString(); }
        if (string.IsNullOrWhiteSpace(containerBaseInfo.MfgOrder.ToString()))
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='无订单开始原因'");
        }
        else
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='订单开始原因'");
        }
        if (datarows.Length > 0) { strStart = datarows[0]["ATTRIBUTEVALUE"].ToString(); }
        containerBaseInfo.StartReason = strStart;
        containerBaseInfo.Level = strLevel;
        containerBaseInfo.Owner = strOwner;

        var serverInfo = new ServerHostInfo();
        serverInfo.UserName = m_UserInfo.APIUserName;
        serverInfo.Password = m_UserInfo.APIPassword;
        containerBaseInfo.ServerHostInfo = serverInfo;
        var result = m_ContainerObj.StartContainer(containerBaseInfo);
        if (result.IsError)
        {
            msg = result.Message;
        }
        else
        {
            //'更新EnginePartPlan表ContainerId
            String Cid = m_ContainerObj.GetContainerData(containerBaseInfo.ContainerName.ToString()).Rows[0]["ContainerID"].ToString();
            m_issueData.UpdateEnginePartPlanID(Cid, containerBaseInfo.ContainerName.ToString());
        }
        return !result.IsError;
    }


}